<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Baidu Map </title>
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=o2MUVkbBwzRNMm9cifUAk6QKiG2o8wt6"></script>
    <script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/vConsole/3.12.1/vconsole.min.js" type="application/javascript"></script>
    <style type="text/css">
        html{height:100%}
        body{height:100%;margin:0px;padding:0px}
        #container{height:100%}
    </style>
</head>
<body>
<div id="msg"></div>
<div id="container"></div>

<script>

    const vConsole = new VConsole();
    var map = new BMapGL.Map("container");          // 创建地图实例
    var point = new BMapGL.Point(116.404, 39.915);  // 创建点坐标
    var myGeo = new BMapGL.Geocoder();
    var mk = new BMapGL.Marker(point)
    var ly = new BMapGL.Label('计算中')
    var driving2 = null;
     map.centerAndZoom(point, 15);                 // 初始化地图，设置中心点坐标和地图级
     map.addOverlay(mk)
    var convertor = new BMapGL.Convertor()
     const transGpsTOBd = (lng,lat)=>{
            return new Promise((resolve,reject)=>{
                convertor.translate([new BMapGL.Point(lng, lat) ],1,5,(res)=>{
                    resolve(res.points[0])
                })
            })

     }


        var h5port;
        var getAddress = (centerPoint)=>{
             myGeo.getLocation(centerPoint, function(result){
                if (result){
                    console.log('result',result)

                    h5port.postMessage(JSON.stringify({type:'addressChange', data: result.content.poi_desc}))
                }
            });
        }
        var setCurPos = async (lng,lat)=>{
            document.querySelector('#msg').innerText = '当前位置'+lng+ ' ' + lat
            // gps设备得到的坐标 叫做大地坐标 wgs84
            // const centerPoint = new BMapGL.Point(lng, lat); // gps的坐标一般不能直接使用
            const centerPoint = await transGpsTOBd(lng,lat);
            console.log('centerPoint',centerPoint)
            map.setCenter(centerPoint)
            mk.setPosition(centerPoint)
            // 逆向解析当前的地址对应的地址信息
            // 根据坐标得到地址描述    
            getAddress(centerPoint)



        }

        var handleEvent = ({ type, data})=>{
              if(type === 'changeTime'){
                  //   document.querySelector('#msg').innerText = data
               }
               if(type === 'setCenter'){
                    // document.querySelector('#msg').innerText = data.latitude+ ' ' + data.longitude
                    console.log('location data', data)
                     setCurPos(data.longitude,data.latitude)
               }
                if(type === 'posChange'){
                   //  document.querySelector('#msg').innerText = data.latitude+ ' ' + data.longitude
                   //  setCurPos(data.latitude,data.longitude)
               }
               if(type === 'setEnd'){
                     driving2 = new BMapGL.DrivingRoute(map, {
                        renderOptions: {
                            map: map,
                            autoViewport: true,
                        },
                        onSearchComplete(result){

                           console.log('规划的结果', result);
                           const plan = result.getPlan(0);
                           const distance = (plan.getDistance(false) / 1000).toFixed(1) +'km';
                           const time  = Math.ceil( plan.getDuration(false) / 60 ) +'分';

                            setTimeout(()=>{
                                    const cp = map.getCenter();
                                    map.removeOverlay(ly)
                                    ly.setContent(`距离:${distance} \n 预计：${time} 达到 `)
                                    ly.setPosition(cp)
                                    map.addOverlay(ly)

                             },1500)
                            h5port.postMessage(JSON.stringify({type:'planOk', data:{
                            distance,
                            time
                            }}))
                        }
                    })
                    const start = mk.getPosition();
                    const end = new BMapGL.Point(data.lng,data.lat);
                    driving2.search(start, end,{})


               }

        }

        window.addEventListener('message',(event)=>{
              // 如果是 __init_port__的消息 我们就初始化h5port
              if(event.data === '__init_port__'){
                 h5port = event.ports[0]
                 h5port.postMessage(JSON.stringify({type:'isready'}))
                 //监听从应用侧发送过来的消息
                 h5port.onmessage = (res)=>{
                     const messageData  = JSON.parse(res.data);
                     handleEvent(messageData) // 根据传过来的消息去执行不同的逻辑

                 }

              }
        })

       // 地图拖拽的监听
       map.on('dragging',(res)=>{
            console.log('res',res)
            const curcenter = map.getCenter();
            mk.setPosition(curcenter)
       })
      map.on('dragend',()=>{
          const curcenter = map.getCenter();
          getAddress(curcenter)
      })
</script>


 <script>

 </script>



</body>
</html>